#include <iostream>
#include <sstream>
#include "csv.h"

csvfile::csvfile()
{
}

csvfile::csvfile(const char* path, char delim, int skip)
{
	load(path, delim, skip);
}

void csvfile::load(const char* path, char delim, int skip)
{
	ifstream fs(path);

	if (!fs.is_open())
	{
		valid = false;
		return;
	}
	
	valid = true;
	int linenum=0;

	while(fs.good())
	{

		vector<float> csvline;

		char line[2048];

		fs.getline(line, 2048);
		string inputstr(line);

		if (linenum++ < skip)
		{
			continue;
		}

		float current;
		stringstream strs(inputstr);

		while(strs >> current)
		{
			csvline.push_back(current);

			if (delim==strs.peek())
			{
				strs.ignore();
				continue;
			}
		}
		data.push_back(csvline);
	}

	fs.close();
}

void csvfile::save(const char* path, char delim)
{
	ofstream fs(path);

	for(vector<vector <float> >::iterator iter = data.begin(); iter != data.end(); iter++)
	{
		vector<float>& line = *iter;

		for(int i = 0; i < line.size(); i++)
		{
			fs << line[i];

			if (i != line.size()-1)
			{
				fs << delim;
			} else 
			{
				fs << endl;
			}
		}
	}

	fs.close();
}
